from time import sleep

from qturboframe.lib.report.log import logger
from qturboframe.lib.utils.CustomError.custom_error import CustomError

from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.public_ui.base_element import BaseElement


class SelectTable(BaseElement):
    '''hui的下拉选择器操作'''

    def __init__(self, element_para, father=None, timeout=5):
        super().__init__(element_para, father, timeout)
        class_list = self._element.get_attribute('class').split(' ')
        if 'h-selectTable' not in class_list:
            temp = self._element.exist(
                'xpath', './ancestor::div[contains(@class, "h-selectTable")]', timeout=self.timeout)
            if not temp:
                temp = self._element.find_element_by_attribute(
                    'css selector', '.h-selectTable', timeout=self.timeout)

            self._element = temp


    def set_value_for_single(self, value, timeout=20):
        """
        hui单选下拉选择器框选择

        :Args:
         - value: 选择项的文本
         - timeout: 超时时间，默认是20s

        :Example:
         - 例1: select.set_value_for_single('苹果')
         - 例2: select.set_value_for_single('苹果',timeout=5)
        """
        select_div_class = r'h-selectTable-dropdown-list'
        self._element.find_element_by_attribute(
            'css selector', 'div.h-selectTable-selection').secure_click()
        input_element = self._element.exist(
            'css selector', 'div.h-selectTable-selection>input', timeout=0.1)
        if input_element:
            input_element.send_keys(value)
        dropdown_div = self._element.exist(
            'css selector', 'div.h-select-dropdown', timeout=0.1)
        if not dropdown_div:
            dropdown_div = self._driver.find_element_by_attribute(
                'xpath', "//body/div[contains(@class,'h-select-dropdown') and not(contains(@style,'display: none'))]",
                timeout=self.timeout)
        timeout1 = 0
        while timeout1 < timeout * 10:
            select_div = dropdown_div.exist('css selector', 'div.' + select_div_class, timeout=0.1)
            if select_div.is_displayed():
                break
            timeout1 += 1
            sleep(0.1)
        else:
            raise SeleniumError('下拉框中没有数据！')
        div = select_div.exist('css selector', 'div.h-table-wrapper', timeout=0.1)
        if not div:
            div = select_div.find_element_by_attribute('xpath', './div', timeout=0.1)
        div_class = div.get_attribute('class').split(' ')
        if 'h-select-block-drop' in div_class:
            select_ul = div.find_element_by_attribute(
                'css selector', 'ul.h-select-blockblock-content', timeout=0.1)
            list_div = div.exist('css selector','div.h-select-block-item-header', timeout=0.1)
            if list_div:
                # 下拉多列列表
                pass
            else:
                select_ul.find_element_by_attribute(
                    'tag name', 'li', 'text:' + value, timeout=self.timeout).secure_click()
        elif 'h-table-wrapper' in div_class:
            div.find_element_by_attribute("xpath",
                                          ".//div[contains(@class,'h-table-cell')]//span[contains(text(),'{}')]".format(
                                              value), timeout=self.timeout).secure_click()

    def clear_for_single(self):
        """
        hui单选下拉框清除选项值

        :Example:
         - 例: select.clear_for_single()
        """
        self._element.move_to()
        self._element.find_element_by_attribute(
            'css selector', 'div.h-selectTable-selection>i.h-icon-close',
            timeout=self.timeout).secure_click()

    def is_default_for_single(self, value):
        """
        检查hui单选下拉框默认值

        :Args:
         - value: 待检查的选项值

        :Returns:
            匹配返回True，否则返回False

        :Example:
         - 例: select.is_default_for_single('香蕉')
        """
        span_value = self._element.find_element_by_attribute(
            'css selector', 'div.h-selectTable-selection>span.h-selectTable-selected-value', timeout=0.1)
        text = span_value.text
        if text:
            if value == text:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        span_default = self._element.exist(
            'css selector', 'div.h-selectTable-selection>span.h-selectTable-placeholder', timeout=0.1)
        if span_default:
            text = span_default.text
            if value == text:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        else:
            logger.error('没有默认值！')
            return False

    def is_nonnull(self):
        '''
        检查hui下拉框是否有非空属性

        :Returns:
            非空返回True，否则返回False

        :Example:
         - 例: select.is_nonnull()
        '''
        self._element.focus()
        form_item = self._element.find_element_by_attribute(
            'xpath', './ancestor::div[contains(@class, "h-form-item-content")]/'
                     'parent::div[contains(@class, "h-form-item")]', timeout=self.timeout)
        item_class_list = form_item.get_attribute('class').split(' ')
        if 'h-form-item-required' in item_class_list:
            return True
        else:
            return False

    def check_default_for_single(self, value):
        """
        检查hui单选下拉框默认值

        :Args:
         - value: 待检查的选项值

        :Raises:
            SeleniumError: 下拉框的默认值校验不通过

        :Example:
         -例: select.check_default_for_single('香蕉')
        """
        if not self.is_default_for_single(value):
            message = '下拉框的默认值校验不通过！'
            raise SeleniumError(CustomError.Error_EQ03016001_Select_Verify_Fail, message)

    def check_nonnull(self):
        '''
        检查hui下拉框是否有非空属性

        :Raises:
            SeleniumError: 下拉框的非空校验不通过

        :Example:
         - 例: select.check_nonnull()
        '''
        if not self.is_nonnull():
            message = '下拉框的非空校验不通过！'
            raise SeleniumError(CustomError.Error_EQ03016001_Select_Verify_Fail, message)
